<template>
  <div>
    <div v-if="!isDisabled" class="mall_style">
      <template v-if="shopInfo && shopInfo.id && shopInfo.statusCode !== 'Closed'">
        <div v-show="!isInCartRoute">
          <div class="mall_page mall_banner gl_mb_20">
            <div class="banner_title">
              <span class="gl_pointer" @click="jumpToShopHome">{{ shopInfo.name }}</span>
            </div>
            <div class="banner_logo">
              <img class="banner_logo_style" :src="getStaticFileUrl(shopInfo.logoUrl)" alt="" @click="jumpToShopHome">
            </div>
            <div class="banner_ctrl">
              <div class="banner_search_wrap">
                <input v-model.trim="searchInput" class="banner_search" type="text" placeholder="请输入商品名称" @keydown.13="searchGoods">
                <i class="banner_input_icon el-icon-search gl_pointer" @click="searchGoods" />
              </div>
              <div style="overflow:hidden" class="gl_clear">
                <el-badge :value="cartTotal" :hidden="cartTotal <= 0" :max="99" class="badge_style gl_fr">
                  <el-button type="primary" size="small" icon="el-icon-shopping-cart-full" @click="toShoppingCart()">我的购物车</el-button>
                </el-badge>
              </div>
            </div>
          </div>
          <div v-show="swiperImgs.length" class="mall_page mall_swiper">
            <swiper ref="mySwiper" :options="swiperOptions">
              <swiper-slide v-for="(item, index) in swiperImgs" :key="index">
                <a :href="item.linkAddress" target="_blank">
                  <img class="img_style" :src="getStaticFileUrl(item.imageUrl)">
                </a>
              </swiper-slide>
              <div slot="pagination" class="swiper-pagination" />
            </swiper>
          </div>
        </div>
        <!-- 路由 -->
        <router-view
          :shop-info="shopInfo"
          :menu-info="menuInfo"
          :recommend-info="recommendInfo"
          @reGetCartInfo="reGetCartInfo"
        />
      </template>
      <template v-if="shopInfo.statusCode === 'Closed'">
        <div class="mall_page shop_closed gl_py_20">
          店铺已被关闭
        </div>
      </template>
    </div>
    <div v-else class="mall_style">
      <template>
        <div class="mall_page shop_closed gl_py_20">
          当前商城已被禁用，请联系平台管理员
        </div>
      </template>
    </div>
  </div>

</template>

<script>
import { mapState } from 'vuex';

import {
  api_GET_MallStoreByRoute, // 查询指定店铺
  api_GET_MallBanner, // 获取轮播图列表
  api_GET_MallProductGroup, // 获取商品分组列表
  api_GET_MallProductRecommend, // 获取店铺的推荐商品
  api_GET_MallShoppingCartCount // 获取购物车数量
} from '@/extend/api/shoppingmallswaggerApi/app.js';
import { getToken } from '@/lib/auth';
import { postLoginMsg } from '@/lib/index';

export default {
  data () {
    return {
      isDisabled: false,
      swiperImgs: [],
      swiperOptions: {
        init: false,
        slidesPerView: 1, // 显示个数
        width: 1200,
        height: 268,
        loop: true,
        autoplay: {
          delay: 3000,
          disableOnInteraction: false
        },
        pagination: {
          el: '.swiper-pagination'
        }
      },
      searchInput: '', // 搜索内容
      shopInfo: {}, // 店铺信息
      cartTotal: 0, // 购物车内商品数量
      menuInfo: [], // 菜单数据（即分组）
      recommendInfo: [], // 推荐商品信息
      registerId: ''
    };
  },
  computed: {
    ...mapState({
      tokenInfo: state => state.user.token || getToken()
    }),
    swiper() {
      return this.$refs.mySwiper.swiper;
    },
    isInCartRoute () { // 路由是否处于购物车页面，如果处于购物车，则不显示顶部区域
      return this.$route.name === 'Settlement' || this.$route.name === 'MyCart' || this.$route.name === 'MyCartSettlement';
    },
    shopRoute () { // 店铺路由
      const _ids = this.$route.params.id.split('_');
      return _ids[0] ? _ids[0] : '';
    }
  },
  beforeRouteUpdate(to, from, next) {
    const toName = to.name;
    const fromName = from.name;
    // 存在registerId， 并且需要进入到商城首页，且 到哪去和从哪来的路由不一致 时，重新获取购物车数量
    if (toName === 'MallHome' && (toName !== fromName)) {
      this.reGetCartInfo();
    }
    next();
  },
  created() {
    // 获取店铺信息
    this.getShopInfo({
      route: this.shopRoute,
      IncludeStatus: true
    });
    this.getCartInfo();
    // this.searchInput = this.$route.query.key || '';
  },
  methods: {
    // 获取店铺信息
    getShopInfo (vo) {
      api_GET_MallStoreByRoute(vo)
        .then(
          res => {
            console.log(res);
            if (res.isDisabled) {
              this.isDisabled = true;
            } else {
              this.isDisabled = false;
            }
            this.shopInfo = res || {};
            if (res && res.id && res.statusCode !== 'Closed') {
              // 获取轮播信息
              this.getSwiperInfo({
                StoreId: res.id,
                IsOnline: true
              });

              // 获取分组信息
              this.getGoodsGroup({
                StoreId: res.id
              });

              // 获取推荐商品信息
              this.getRecommendList({
                SkipCount: 0,
                MaxResultCount: 8,
                StoreId: res.id,
                IncludeProduct: true,
                IncludeImages: true,
                IncludeGroup: true
              });
            }
          }
        )
        .catch(
          // error => {
          //   this.$message({
          //     message: `店铺信息获取失败！ ${error.error.message}`,
          //     type: 'error',
          //     showClose: true
          //   });
          // }
        );
    },
    // 获取购物车信息
    getCartInfo () {
      api_GET_MallShoppingCartCount()
        .then(
          res => {
            this.cartTotal = res || 0;
          }
        );
    },
    // 重新获取购物车信息
    reGetCartInfo () {
      this.getCartInfo();
    },
    // 获取商品分组列表
    getGoodsGroup (qo) {
      api_GET_MallProductGroup(qo)
        .then(
          res => {
            if (res && res.items) {
              const _all = {
                description: '本店所有商品',
                id: '_all',
                isDeleted: false,
                name: '本店所有商品',
                sortOrder: -1
              };
              this.menuInfo = [_all, ...res.items];
            }
          }
        );
    },
    // 获取推荐商品列表
    getRecommendList (qo) {
      api_GET_MallProductRecommend(qo)
        .then(
          res => {
            if (res) {
              const _list = res.items || [];
              this.recommendInfo = _list.filter(item => item.product.productStatusCode === 'OnShelf');
            }
          }
        );
    },
    // 获取轮播图信息
    getSwiperInfo (qo) {
      api_GET_MallBanner(qo)
        .then(
          res => {
            this.swiperImgs = res || [];
            this.$nextTick(() => {
              // 需要数据取到后并渲染完swiper再初始化init,
              this.swiper.init();
            });
          }
        );
    },
    // 跳转至商城首页
    jumpToShopHome () {
      if (this.$route.params.id) {
        this.$router.push({
          path: `/home/${this.$route.params.id}`
        });
      }
    },
    // 去往我的购物车
    toShoppingCart() {
      if (!this.tokenInfo) {
        // 嵌入式
        if (this.$route.params.id.indexOf('_plat') === -1) {
          postLoginMsg();
          return false;
        }
      }
      this.$router.push({
        name: 'MyCart'
      });
    },
    // 搜索店铺商品
    searchGoods () {
      if (this.searchInput) {
        this.$router.push({
          name: 'MallSearch',
          query: {
            key: this.searchInput
          }
        });
      } else {
        this.jumpToShopHome();
      }
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    }
  }
};
</script>

<style>
  .el-badge__content.is-fixed {
    right: 35px;
  }

  .mall_style .mall_page {
    width: 1200px;
    margin: 0 auto;
  }
  .mall_style .mall_content {
    padding: 40px 12px 0;
    background: #fff;
    border-radius: 0px 0px 8px 8px;
    box-shadow: 0px 20px 80px 0px rgba(0,0,0,0.10);
  }
  /* 标题 */
  .mall_style .goods_title {
    overflow: hidden;
    padding: 0 10px 6px;
    line-height: 20px;
    font-size: 14px;
    font-weight: 400;
    color: #353434;
    border-bottom: 1px solid #BDBDBD;
  }
  /* 导航菜单 */
  .mall_style .mall_menu {
    width: 180px;
  }
  .mall_style .mall_menu_item {
    box-sizing: border-box;
    width: 180px;
    height: 48px;
    padding-left: 24px;
    color: #353434;
    font-size: 16px;
    font-weight: 400;
    line-height: 48px;
    border-radius: 4px;
    cursor: pointer;
  }
  .mall_style .mall_menu_item.active {
    color: #fff;
    background: #31456c;
  }
  /* 商品小模块 */
  .mall_style .goods_item {
    box-sizing: border-box;
    width: 176px;
    height: 250px;
    padding: 5px 7px 0;
    transition: 0.3s;
    cursor: pointer;
  }
  .mall_style .goods_item:hover {
    box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
  }
  .mall_style .goods_item_imgWrap,
  .mall_style .goods_item_img {
    width: 162px;
    height: 162px;
  }
  .mall_style .goods_item_img {
    vertical-align: top;
  }
  .mall_style .goods_item_price {
    margin-bottom: 3px;
    font-size: 16px;
    font-weight: 400;
    line-height: 25px;
    color: #e02020;
  }
  .mall_style .goods_item_yuan {
    font-size: 14px;
  }
  .mall_style .goods_item_desc {
    width: 100%;
    height: 40px;
    line-height: 20px;
    font-size: 14px;
    font-weight: 400;
    color: #353434;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    word-break: break-all;
  }
  .mall_style .main_goods {
    overflow: hidden;
  }
</style>

<style lang="scss" scoped>
  .badge_style {
    margin-top: 10px;
  }

  // banner
  .mall_banner {
    box-sizing: border-box;
    position: relative;
    height: 160px;
    padding-top: 15px;
  }
  .banner_title {
    line-height: 40px;
    font-size: 28px;
    font-weight: 400;
    color: #000;
    margin-bottom: 8px;
  }
  .banner_logo {
    width: 200px;
    height: 90px;
  }
  .banner_logo_style {
    width: 100%;
    height: 100%;
    cursor: pointer;
  }
  .banner_ctrl {
    position: absolute;
    right: 0;
    bottom: 24px;
  }
  .banner_search {
    box-sizing: border-box;
    width: 226px;
    height: 36px;
    padding: 0 40px 0 16px;
    line-height: 36px;
    color: #000;
    font-size: 14px;
    background-color: #C3D8FE;
    outline: none;
    border: none;
    border-radius: 18px;
  }
  .banner_search_wrap {
    position: relative;
    margin-bottom: 41px;
  }
  .banner_input_icon {
    position: absolute;
    right: 16px;
    top: 10px;
  }

  // swiper
  .swiper-container {
    width: 100%;
    height: 100%;
  }
  .mall_swiper {
    height: 268px;
  }
  .img_style {
    width: 100%;
    height: 100%;
    cursor: pointer;
  }

  .shop_closed {
    text-align: center;
  }
</style>
